package com.icd.backend.srevice.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.icd.backend.bean.dto.UserDTO;
import com.icd.backend.bean.dto.UserQueryDTO;
import com.icd.backend.bean.entity.User;
import com.icd.backend.mapper.UserMapper;
import com.icd.backend.srevice.UserService;
import com.inspur.icd.common.service.BaseCrudServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserServiceImpl extends BaseCrudServiceImpl<UserMapper, User, JSONObject> implements UserService {

    @Override
    public User create(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        user.setStatus(1); // 默认启用

        this.save(user);
        return user;
    }

    @Override
    public User update(String id, UserDTO userDTO) {
        User existingUser = this.getById(id);
        if (existingUser == null) {
//            throw new Exception();
        }

        BeanUtils.copyProperties(userDTO, existingUser);
        if (userDTO.getPassword() != null) {
            existingUser.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        }
        this.updateById(existingUser);
        return existingUser;
    }

    @Override
    public void delete(String id) {
        if (this.getById(id) == null) {
//            throw new BusinessException("用户不存在");
        }
        this.delete(id);
    }

    @Override
    public User getById(String id) {
        User user = this.getById(id);
        if (user == null) {
//            throw new BusinessException("用户不存在");
        }
        return user;
    }

    @Override
    public PageInfo<User> list(UserQueryDTO queryDTO) {
        IPage<User> iPage = new Page<>();
        iPage.setCurrent(queryDTO.getPageNum());
        iPage.setSize(queryDTO.getPageSize());

        List<User> users = this.list(iPage);
        return new PageInfo<>(users);
    }
}
